package com.qf.watcher;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class CuratorWatcher02 {
    private static final String ZKADDR = "10.9.12.200:8601,10.9.12.200:8602,10.9.12.200:8603";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);//用作阻塞的, 1 的意思是只需有一个地方执行了放行就放行所有阻塞的地方

    public static void main(String[] args) throws Exception {
        //        创建一个curator 工厂   指定连接地址   超时时间
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(ZKADDR)
                .connectionTimeoutMs(5000)//超时时间
//                  失败后会等一秒在重试    最多重试5 次    等于最多连接6 次
                .retryPolicy(new ExponentialBackoffRetry(1000, 5))//如果连接不上 是否重试    怎么重试
                .build();

        curatorFramework.start();
//      节点惠存
        NodeCache nodeCache=new NodeCache(curatorFramework, "/super4",false);
        nodeCache.start(true);//开启缓存机制  为监听做贡献
        System.out.println("555555555");
        nodeCache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("111111111");
                System.out.println(nodeCache.getCurrentData().getPath());
                System.out.println(nodeCache.getCurrentData().getData());
                System.out.println(nodeCache.getCurrentData().getStat());
            }
        });

        System.out.println("22222222222");
        curatorFramework.create().forPath("/super4","111".getBytes(StandardCharsets.UTF_8));


        System.in.read();


    }
}
